package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService {
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Override
    public PageResult page(StudentQueryParam studentQueryParam) {
        // 1. 设置分页参数
        PageHelper.startPage(studentQueryParam.getPage(), studentQueryParam.getPageSize());
        
        // 2. 执行查询
        List<Student> studentList = studentMapper.page(studentQueryParam);
        
        // 3. 封装分页结果
        Page<Student> page = (Page<Student>) studentList;
        
        return new PageResult(page.getTotal(), page.getResult());
    }
    @Override
    public void deleteByIds(List<Integer> ids) {
        studentMapper.deleteByIds(ids);
    }

    @Override
    public void save(Student student) {
        studentMapper.insert(student);
    }

    @Override
    public Student getById(Integer id) {
        return studentMapper.getById(id);
    }

    @Override
    public void update(Student student) {
        // 设置更新时间
        student.setUpdateTime(LocalDateTime.now());
        // 调用 Mapper 或 Repository 执行更新操作
        studentMapper.update(student);
    }

    @Override
    public void violation(Integer id, Short score) {
        // 查询学员信息
        Student student = studentMapper.getById(id);
        if (student != null) {
            // 增加违纪次数
            student.setViolationCount((short)(student.getViolationCount() + 1));
            // 扣除分数
            student.setViolationScore((short)(student.getViolationScore() + score));
            // 更新时间
            student.setUpdateTime(LocalDateTime.now());
            // 更新学员信息
            studentMapper.update(student);
        }
    }

    @Override
    public List<DegreeStatistics> getDegreeStatistics() {
        return studentMapper.getDegreeStatistics();
    }
    @Override
    public ClazzStatistics getClazzStatistics() {
        // 获取统计结果
        List<ClazzCount> statistics = studentMapper.getClazzStatistics();

        // 分别提取班级名称和人数
        List<String> clazzList = new ArrayList<>();
        List<Integer> dataList = new ArrayList<>();

        for (ClazzCount item : statistics) {
            clazzList.add(item.getClazzName());
            dataList.add(item.getStudentCount());
        }

        return new ClazzStatistics(clazzList, dataList);
    }





}
